#!/bin/sh

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <skarvin@gmail.com>

# ----------------------------------------------------------------------------
# desc: Motion camera files generation
# author: Isidro Catalan <skarvin@gmail.com>, http://www.opendomo.com
# date: October 2008
#
# CHANGES:
#   13-10-2008	skarvin GPLv3
#   15-10-2008	skarvin Some bug fixes
#	21-10-2008  skarvin Environment vars
#   13-12-2010  opalenzuela Some stderr omitted
# ----------------------------------------------------------------------------

if ! test -f "/etc/opendomo/videoConfVars.conf"; then
   cp /etc/opendomo/videoConfVars.conf.orig /etc/opendomo/videoConfVars.conf
fi
# Common video module vars
. "/etc/opendomo/videoConfVars.conf"

# Lib config
. "$LIB_CONFIG"

# Todo, contemplar los casos en los que Nfs y samba es seleccionado
# de momento Not working...

# Target dir overwriting when Dir is specified
CONF_FILE="/etc/opendomo/motion.conf"
VIDEOZONES="/etc/opendomo/video"

# Obtaining params
TYPE=$1
ACTION=$2
CAMID=$3
NETCAM_URL=$4
NETCAM_AUTH=$5

createMotionConf ()
{

  # Check if the motion config file is already set
  if ! test -f "$CONF_FILE"; then
     cp /etc/opendomo/motion.conf.orig /etc/opendomo/motion.conf
     mkdir /tmp/video 2> /dev/null
     chown admin:admin /tmp/video 2>/dev/null
  fi
  
  if [ ! -d "$VIDEOZONES" ]; then
		mkdir "$VIDEOZONES"
  fi
}

# Crea el fichero si no existe si no no hace nada
createMotionConf
TARGET_DIR=`getValue "target_dir"`

showUsage ()
{
   echo " Missing parameters!
   
   Usage: 
   $0 usb add id_camera <- this generates the config file for a usb camera
   $0 usb remove id_camera <- this removes the config file for a usb camera
   $0 ip add name_cam netcam_url netcam_userpass <- this adds the config file for an IP camera             
   $0 ip remove name_cam netcam_url netcam_userpass <- this removes the config file for an IP camera                
   "
}

# Obtiene el numero de camaras configuradas
getNumPort ()
{
   last_port=`ls $MTN_CNF_PATH | grep odcam- | cut -d"-" -f2 | sort -r | head -n1`

	if [ -z "$last_port" ]; then
		res=`expr $START_PORT + 1`
	else
		res=`expr $last_port + 1`	
	fi
	
	echo $res
}

# Recibe el Id de la camara y el puerto
createMotionThread ()
{
local CAM_PORT
local CAMID
CAMID=$1
CAM_PORT=$2
echo "
videodevice $DEV_PATH/$CAMID
input 8
text_left $3
target_dir $TARGET_DIR/odcam-$CAM_PORT-usb
webcam_port $CAM_PORT
movie_filename cam_$CAMID-%Y%m%d%H%M%S
jpeg_filename cam_$CAMID-%Y%m%d%H%M%S
on_motion_detected /bin/logevent info odvideo "Motion detected on camera [$4]"
on_camera_lost /bin/logevent error odvideo "Camera [$CAMID] has been lost!"
on_picture_save /bin/logevent warning odvideo "Motion detected on camera [$4]" %f

" > $MTN_CNF_PATH/odcam-$CAM_PORT-usb.conf

}

# Recibe el puerto para acceder a la camara
createMotionThreadIP ()
{
local CAM_PORT
local NETCAM_URL
local NETCAM_AUTH
local CAMID
CAMID=$1
CAM_PORT=$2
NETCAM_URL=$3
NETCAM_AUTH=$4
echo "
netcam_url $NETCAM_URL
input 1
text_left $CAMID
target_dir $TARGET_DIR/odcam-$CAM_PORT-ip
webcam_port $CAM_PORT
netcam_userpass $NETCAM_AUTH
movie_filename cam_$CAMID-%Y%m%d%H%M%S
jpeg_filename cam_$CAMID-%Y%m%d%H%M%S
on_motion_detected /bin/logevent info odvideo "Motion detected on camera [$CAMID]"
on_camera_lost /bin/logevent error odvideo "Camera [$CAMID] has been lost!"
on_picture_save /bin/logevent warning odvideo "Motion detected on camera [$CAMID]" %f

" > $MTN_CNF_PATH/odcam-$CAM_PORT-ip.conf
}

cleanCam ()
{
   for i in `ls $MTN_CNF_PATH/odcam-* 2>/dev/null`; do
		if grep -q "$CAMPREFIX$CAMID" "$i" ; then
		   port=`awk -F" " '/^webcam_port/ { print $2 }' $i`   
		   rm "$MTN_CNF_PATH/odcam-$port-$TYPE.conf" 2>/dev/null		
		   # Delete the zone file
		   rm "$VIDEOZONES/odcam-$CAMID-$TYPE.info" 2>/dev/null				   
  		   # Eliminamos la linea correaspondiente al hilo
	      cat $MTN_CNF_PATH/motion.conf | grep -v "odcam-$port-$TYPE.conf" > /tmp/mtn.tmp
	      cat /tmp/mtn.tmp > $MTN_CNF_PATH/motion.conf && rm /tmp/mtn.tmp
		fi
   done
}

cleanConfigFiles ()
{

 	for i in `ls $MTN_CNF_PATH/odcam-* 2>/dev/null`; do
	   port=`awk -F" " '/^webcam_port/ { print $2 }' $i`   
	   rm "$MTN_CNF_PATH/odcam-$port-$TYPE.conf" 2>/dev/null		
	   # Eliminamos la linea correaspondiente al hilo
	   cat $MTN_CNF_PATH/motion.conf | grep -v "odcam-$port" > /tmp/mtn.tmp
	   cat /tmp/mtn.tmp > $MTN_CNF_PATH/motion.conf && rm /tmp/mtn.tmp
	done
}

camExists ()
{
   for i in `ls $VIDEOZONES/odcam-* 2>/dev/null`; do
		if grep -q "$CAMPREFIX$CAMID" "$i" ; then
		 echo "1"
		fi
   done
   echo "0"
}



if [ "$#" -lt 2 ]; 
then
   showUsage   
elif [ "$ACTION" = "add" ] && [ "$TYPE" = "usb" ]; then
	cam_exists=$(camExists)
	if [ -e "$DEV_PATH/$CAMPREFIX$CAMID" ] && [ "$cam_exists" = "0" ]; then
		echo "# Creating config file for opendomo camera $CAMID"
		PORT=$(getNumPort)   
		echo "# Generating .info file"
		echo "code=\"usbcam$CAMID\"
description=\"Not configured\"
zone=\"Not configured\"
type=\"Not configured\"
connection=\"$TYPE\"		
dev=\"$CAMPREFIX$CAMID\"
port=\"$PORT\"" > $MTN_CNF_PATH/video/odcam-$PORT-$TYPE.info
	/bin/chown admin:admin "$MTN_CNF_PATH/video/odcam-$PORT-$TYPE.info" 2>/dev/null

	else
		echo "# Info file for opendomo camera $CAMID exists!"
	fi
elif [ "$ACTION" = "generate" ] && [ "$TYPE" = "all" ]; then

	# Limpiamos configuraciones previas
	cleanConfigFiles
	# Create motion thread config files 
	
	for i in `ls $VIDEOZONES/odcam-*.info 2>/dev/null`; do
		. $i
		echo "# Adding thread file to motion.conf"
		echo "
thread $MTN_CNF_PATH/odcam-$port-$connection.conf" >> $MTN_CNF_PATH/motion.conf

		echo "# Creating thread file for camera $code"
		if [ "$connection" = "usb" ]; then
			createMotionThread "$dev" "$port" "$description" "$code"
		else
			createMotionThreadIP "$code" "$port" "$netcam_url" "$netcam_auth"
		fi

		/bin/chown admin:admin "$MTN_CNF_PATH/odcam-$port-$connection.conf" 2>/dev/null
		echo "# Creating captures folder"
		mkdir -p $TARGET_DIR/odcam-$port-$connection 2>/dev/null
		/bin/chown admin:admin "$TARGET_DIR/odcam-$port-$connection"  2>/dev/null
		/bin/chown admin:admin "$MTN_CNF_PATH/odcam-$port-$connection.conf" 2>/dev/null
	done
 
    return 0
	
elif [ "$ACTION" = "remove" ] && [ "$TYPE" = "usb" ]; then
   echo "# Removing config file for opendomo camera $CAMID"
   cleanCam
elif [ "$ACTION" = "add" ] && [ "$TYPE" = "ip" ]; then
		echo "# Creating config file for opendomo camera $CAMID"
		PORT=$(getNumPort)   
		echo "# Generating .info file"
		echo "code=\"ipcam$CAMID\"
description=\"Not configured\"
zone=\"Not configured\"
type=\"Not configured\"
connection=\"$TYPE\"
netcam_url=\"$NETCAM_URL\"
netcam_auth=\"$NETCAM_AUTH\"
port=\"$PORT\"" > $MTN_CNF_PATH/video/odcam-$PORT-$TYPE.info

    return 0
	
elif [ "$ACTION" = "remove" ] && [ "$TYPE" = "ip" ]; then

	echo "# Removing IP Camera [$CAMID]"

	if grep -q "odcam-$CAMID-$TYPE.conf" "$MTN_CNF_PATH/motion.conf" ; then
	   rm "$MTN_CNF_PATH/odcam-$CAMID-$TYPE.conf" 2>/dev/null	
	   # Delete the zone file
   	   rm "$VIDEOZONES/odcam-$CAMID-$TYPE.info" 2>/dev/null		
	   # Eliminamos la linea correaspondiente al hilo
      grep -v "odcam-$CAMID-$TYPE.conf" < $MTN_CNF_PATH/motion.conf > /tmp/mtn.tmp && cat /tmp/mtn.tmp > $MTN_CNF_PATH/motion.conf && rm /tmp/mtn.tmp
	else
		echo "#ERR: No se ha encontrado la camara especificada"      
	fi
    return 0

else
   echo "# Unknown action"
   showUsage
fi

chown admin:admin /etc/opendomo/motion.conf /etc/opendomo/odcam* /etc/opendomo/video/* 2>/dev/null
chmod 0664 /etc/opendomo/motion.conf /etc/opendomo/odcam* 2>/dev/null
